package com.sun.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Author Sun
 * @Date 2020/4/20 10:46
 * @Version 1.0
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应编码，以免输出参数乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");//获取单个参数
        String pwd = req.getParameter("pwd");
        String[] hobbies = req.getParameterValues("hobbies");//获取多选框里的多个参数
        System.out.println(username+":"+pwd);
        System.out.println(Arrays.toString(hobbies));

        //通过响应重定向,---getContextPath()方法可以得到项目访问根目录：/req
        //resp.sendRedirect(req.getContextPath()+"/success.jsp");

        //通过servletContext转发，不推荐
        //this.getServletContext().getRequestDispatcher("/success.jsp").forward(req, resp);

        //通过请求转发，这是服务器端级别，会自动加上项目路径
        req.getRequestDispatcher("/success.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
